# -*- coding: utf-8 -*-
class PrivilegeController < ApplicationController
  before_filter :sys_before_log
  #before_filter :privilege_filter,:except=>[:newPrivilegeDetail,:editPrivilegeDetail,:newPrivilegeModule,:editPrivilegeModule,:newPrivilegeMenu,:editPrivilegeMenu,:rolePrivilegeDetailLock]

  #系统权限主页面
  def systemPrivilege

  end

  #根据ID得到系统权限树，如果id为空，则表示得到根节点下所有节点。
  def getSysPrivilegeChildrenById
    nodeId =  params["node"]
    #作一些处理，因为传来的nodeId可能出现怪值。
    if nodeId == nil || (nodeId.include? "xnode-") || nodeId == "0"
      is_root = true
      nodeId = 0
    end
    privileges  = Privilege.find(:all,:conditions=>["parent_id = ?",nodeId],:order=>'sort_id')
    treeData="["
    privileges.each do |privilege|
      treeData.concat("{id:#{privilege.id},text:\"#{privilege.name}\"")
      if privilege.level == 0
        treeData.concat(",leaf:false")
      else
        treeData.concat(",leaf:true")
      end

      if privilege.is_locked == 1
        treeData.concat(",checked:true},")
      else
        treeData.concat(",checked:false},")
      end
    end
    treeData = treeData[0,treeData.size-1]
    treeData.concat("]")
    logger.info treeData
    jsonStr = treeData
    #jsonStr = "[{\"text\":\"pkgs\",\"id\":\"\/pkgs\",\"cls\":\"folder\"},{\"text\":\"INCLUDE_ORDER.txt\",\"id\":\"\/INCLUDE_ORDER.txt\",\"leaf\":true,\"cls\":\"file\"},{\"text\":\"gpl-3.0.txt\",\"id\":\"\/gpl-3.0.txt\",\"leaf\":true,\"cls\":\"file\"},{\"text\":\"CHANGES_ext-3.1.0.html\",\"id\":\"\/CHANGES_ext-3.1.0.html\",\"leaf\":true,\"cls\":\"file\"},{\"text\":\"adapter\",\"id\":\"\/adapter\",\"cls\":\"folder\"},{\"text\":\"examples\",\"id\":\"\/examples\",\"cls\":\"folder\"},{\"text\":\"docs\",\"id\":\"\/docs\",\"cls\":\"folder\"},{\"text\":\"ext-all.js\",\"id\":\"\/ext-all.js\",\"leaf\":true,\"cls\":\"file\"},{\"text\":\"ext.jsb2\",\"id\":\"\/ext.jsb2\",\"leaf\":true,\"cls\":\"file\"},{\"text\":\"license.txt\",\"id\":\"\/license.txt\",\"leaf\":true,\"cls\":\"file\"},{\"text\":\"ext-all-debug.js\",\"id\":\"\/ext-all-debug.js\",\"leaf\":true,\"cls\":\"file\"},{\"text\":\"resources\",\"id\":\"\/resources\",\"cls\":\"folder\"},{\"text\":\"src\",\"id\":\"\/src\",\"cls\":\"folder\"}]"
    render :text=>jsonStr, :layout=>false
  end

  def updateSysPrivilege
    begin
      privilege = Privilege.find(params[:id])
      #Privilege.transaction do
      privilege.name = params[:name]
      privilege.description = params[:description]
      #0代表是在根下直接添加。

      if params[:parent_id].to_i > 0
        privilege.parent_id = params[:module_id]
        privilege.sys_controller_id = params[:sys_controller_id]
        privilege.sys_action_id = params[:sys_action_id]
        #然后把所有角色的相关权限都修改一下。
        RolesPrivilegeDetail.update_all("module_id = #{privilege.parent_id}","menu_id = #{privilege.id}")
      end
      #privilege.leaf = "true"
      privilege.save
      #end
    rescue Exception => e
      logger.info e
      logger.info "在提交事务时，发生错误。!!!!!!!!!!!!!!!!!!!"
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #创建系统权限
  def createSysPrivilege
    begin
      privilege = Privilege.new
      #Privilege.transaction do
      privilege.name = params[:name]
      privilege.description = params[:description]
      privilege.parent_id = params[:parent_id]
      #0代表是在根下直接添加。
      if privilege.parent_id == 0
        privilege.level = 0
      else
        privilege.level = 1
        privilege.sys_controller_id = params[:sys_controller_id]
        privilege.sys_action_id = params[:sys_action_id]
      end
      #privilege.leaf = "true"
      privilege.save
      #如果在非根节点添加了权限，要把上一级权限的CSS设定为leaf=false
      if privilege.parent_id != 0
        parentPrivilege = Privilege.find(privilege.parent_id)
        parentPrivilege.leaf = "false"
        parentPrivilege.save!
      end

      #设置最大的排序Id号
      maxSortId = Privilege.where("parent_id = ?",privilege.parent_id ).maximum(:sort_id)
      privilege.sort_id = maxSortId + 1
      privilege.save
      #end
    rescue Exception => e
      logger.info e
      logger.info "在提交事务时，发生错误。!!!!!!!!!!!!!!!!!!!"
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #删除主权限
  def destroySysPrivilege
    Privilege.destroy(params[:id])
    RolesPrivilegeDetail.destroy_all(["module_id = ?" , params[:id]])
    RolesPrivilegeDetail.destroy_all(["menu_id = ?" , params[:id]])
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #为编辑模块，准备数据。
  def getSysPrivilegeById
    #编辑前的数据准备
    privilege = Privilege.find(:all, :include=>[:sys_controller,:sys_action], :conditions=>["id = ?",params[:id]])
    rootStr = privilege.to_json(:include=>[:sys_controller,:sys_action])
    jsonStr = "{root:"+rootStr+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end


  #详细权限的解锁与锁定,
  def rolePrivilegeDetailLock
    RolesPrivilegeDetail.transaction do
      rolesPrivilegeDetail = RolesPrivilegeDetail.find(params[:id])
      if rolesPrivilegeDetail.is_locked == 1
        rolesPrivilegeDetail.is_locked = 0
      else
        rolesPrivilegeDetail.is_locked = 1
      end
      rolesPrivilegeDetail.save!
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #详细权限的解锁与锁定
  def privilegeDetailLock
    RolesPrivilegeDetail.transaction do
      privilegeDetail = PrivilegeDetail.find(params[:id])
      if privilegeDetail.is_locked == 1
        privilegeDetail.is_locked = 0
      else
        privilegeDetail.is_locked = 1
      end
      privilegeDetail.save!
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end


  #创建权限细节。
  def createSysPrivilegeDetail
    begin
      privilegeDetail = PrivilegeDetail.new
      privilegeDetail.privilege_id = params[:privilege_id]
      privilegeDetail.name = params[:name]
      privilegeDetail.sys_controller_id = params[:sys_controller_id]
      privilegeDetail.sys_action_id = params[:sys_action_id]
      privilegeDetail.sub_type = params[:sub_type]
      privilegeDetail.params = params[:params]
      privilegeDetail.description = params[:description]
      privilegeDetail.save!
    rescue Exception => e
      info = e
      DbLog.info(params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #编辑后，更新权限细节。
  def updateSysPrivilegeDetail
    begin
      RolesPrivilegeDetail.transaction do
        privilegeDetail = PrivilegeDetail.find(params[:id])
        privilegeDetail.name = params[:name]
        privilegeDetail.sys_controller_id = params[:sys_controller_id]
        privilegeDetail.sys_action_id = params[:sys_action_id]
        privilegeDetail.sub_type = params[:sub_type]
        privilegeDetail.params = params[:params]
        privilegeDetail.description = params[:description]
        privilegeDetail.save!
      end
    rescue Exception => e
      info =
        logger.info "Exception:------------------------------------------------------------------"
      logger.info e
      CommonHelper.infoLogger(session[:employee_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #删除子权限
  def destroySysPrivilegeDetail
    PrivilegeDetail.transaction do
      PrivilegeDetail.destroy(params[:id])
      RolesPrivilegeDetail.destroy_all(["privilege_detail_id = ?" , params[:id]])
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  #得到系统某一权限的详细项。
  def getPrivilegeDetailsById
    begin
      logger.info params[:privilege_id]
      privilegeDetails = PrivilegeDetail.find(:all,:include=>[:sys_controller,:sys_action],:conditions=>["privilege_id = ?",params[:privilege_id]])
      jsonStr="{totalProperty:"+privilegeDetails.length.to_s+",root:"+privilegeDetails.to_json(:include=>[:sys_controller,:sys_action])+"}"
    rescue Exception => e
      logger.info "Exception:------------------------------------------------------------------"
      logger.info e
    end
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #根据ID得到某一条权限细节。
  def getPrivilegeDetailById
    privilegeDetail = PrivilegeDetail.find(params[:id])
    rootStr = privilegeDetail.to_json()
    jsonStr = "{root:["+rootStr+"]}"
    render :text=>jsonStr, :layout=>false
  end

  #下移权限的排序
  def sortUp
    privilege = Privilege.find(params[:id])
    #等于0，说明是模块级，非0代表是菜单级
    if privilege.parent_id == 0
      previousPrivilege = Privilege.find(:first,:conditions=>["parent_id = 0 AND sort_id = ?",privilege.sort_id-1])
      if previousPrivilege != nil
        privilege.sort_id = privilege.sort_id - 1
        privilege.save!
        previousPrivilege.sort_id = previousPrivilege.sort_id + 1
        previousPrivilege.save!
      end
    else
      previousPrivilege = Privilege.find(:first,:conditions=>["parent_id = ? AND sort_id = ?",privilege.parent_id,privilege.sort_id-1])
      if previousPrivilege != nil
        privilege.sort_id = privilege.sort_id - 1
        privilege.save!
        previousPrivilege.sort_id = previousPrivilege.sort_id + 1
        previousPrivilege.save!
      end
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def sortDown
    privilege = Privilege.find(params[:id])
    #等于0，说明是模块级，非0代表是菜单级
    if privilege.parent_id == 0
      nextPrivilege = Privilege.find(:first,:conditions=>["parent_id = 0 AND sort_id = ?",privilege.sort_id+1])
      if nextPrivilege != nil
        privilege.sort_id = privilege.sort_id + 1
        privilege.save!
        nextPrivilege.sort_id = nextPrivilege.sort_id - 1
        nextPrivilege.save!
      end
    else
      nextPrivilege = Privilege.find(:first,:conditions=>["parent_id = ? AND sort_id = ?",privilege.parent_id,privilege.sort_id+1])
      if nextPrivilege != nil
        privilege.sort_id = privilege.sort_id + 1
        privilege.save!
        nextPrivilege.sort_id = nextPrivilege.sort_id - 1
        nextPrivilege.save!
      end
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
end
